<template>
  <div class="app-container-flex">
    <NewFullScreen v-model="showDialog" :title="title">
      <template v-slot:full-button>
        <el-button :disabled="!canSave" @click="save()">保存</el-button>
      </template>
      <div class="model-panel">
        <div class="model-panel-title">
          <p>{{ $t('basic_information') }}</p>
        </div>
        <div class="model-panel-body">
          <!-- form -->
          <page-form
            class="paddingBox order-model-formBox flex_wrap_start_start"
            v-model:ref-obj="formInfo.ref"
            :disabled="formInfo.disabled"
            :data="formInfo.data"
            :field-list="formInfo.fieldList"
            :rules="formInfo.rules"
            :label-width="formInfo.labelWidth"
          >
            <template v-slot:form-depotName>
              <el-input
                v-model="formInfo.data.depotName"
                class="not-mongolia"
                :disabled="true"
                placeholder="请选择领入仓库"
              >
              </el-input>
            </template>
            <template v-slot:form-exportDepotName>
              <el-input
                v-model="formInfo.data.exportDepotName"
                class="not-mongolia"
                type="input"
                :disabled="true"
                placeholder="请选择领出仓库"
              >
              </el-input>
            </template>
          </page-form>
        </div>
      </div>
      <div class="model-panel">
        <div class="model-panel-title">
          <Tooltip :text="$t('detailInfo')" />
        </div>
        <div class="model-panel-body">
          <div class="flex_full_item">
            <el-form ref="tableForm" :model="tableInfo" style="width: 100%">
              <!-- 表格 -->
              <page-table
                :refresh="tableInfo.refresh"
                :init-curpage="tableInfo.initCurpage"
                v-model:data="tableInfo.data"
                :pager="false"
                :summary="true"
                :summary-field-list="tableInfo.summaryFieldList"
                :tab-index="true"
                :query="filterInfo.query"
                :field-list="tableInfo.fieldList"
                :handle="tableInfo.handle"
                :check-box="false"
                :isDynamic="true"
                @handleEvent="handleEvent"
              >
                <template v-slot:col-licenseNumber="scope">
                  <p>{{ scope.row.licenseNumber || '-' }}</p>
                  <p>{{ scope.row.brandName || '-' }}</p>
                </template>
                <template v-slot:col-commonName="scope">
                  <p>{{ scope.row.commonName || '-' }}</p>
                  <p>{{ scope.row.productCode || '-' }}</p>
                  <p>{{ scope.row.alias || '-' }}</p>
                </template>
                <template v-slot:col-type="scope">
                  <p>{{ scope.row.productTypeValue || '-' }}</p>
                  <p>{{ scope.row.codeTypeValue || '-' }}</p>
                  <p>{{ scope.row.classifyValue || '-' }}</p>
                </template>
                <template v-slot:col-standard="scope">
                  <p>{{ scope.row.standard || '-' }}</p>
                  <p>{{ scope.row.unitName || '-' }}</p>
                </template>
                <template v-slot:col-qty="scope">
                  <el-form-item
                    v-if="scope.row.qtyOperateMode !== 3"
                    class="margin-bottom"
                  >
                    <div class="page-table-input-number-wrapper">
                      <div class="page-table-input-number-left">
                        <div class="page-table-input-number-item">
                          <el-form-item
                            :prop="`data.${scope.$index}.largeUnitQty`"
                            :rules="
                              scope.$index >= 0
                                ? [
                                    {
                                      validator: $validate.positiveAndZero,
                                      trigger: ['blur', 'change'],
                                    },
                                  ]
                                : []
                            "
                          >
                            <el-input-number
                              v-model.lazy="scope.row.largeUnitQty"
                              style="width: 100%"
                              clearable
                              controls-position="right"
                              :precision="
                                scope.row.qtyOperateMode === 0 ||
                                scope.row.qtyOperateMode === 2
                                  ? 0
                                  : systemConfig.qty_show_precision
                              "
                              :min="0"
                              :max="99999999"
                              @change="
                                changeLarge(
                                  $event,
                                  `data.${scope.$index}.largeUnitQty`
                                )
                              "
                            />
                          </el-form-item>
                          <div class="page-table-input-number-item-unite">
                            {{ scope.row.unitName }}
                          </div>
                        </div>
                        <div
                          v-if="
                            scope.row.unitConvertCoefficient > 1 &&
                            scope.row.qtyOperateMode === 2
                          "
                          class="page-table-input-number-item"
                        >
                          <el-form-item>
                            <el-input-number
                              v-model.lazy="scope.row.smallUnitQty"
                              style="width: 100%"
                              clearable
                              controls-position="right"
                              :precision="0"
                              :min="0"
                              :max="scope.row.unitConvertCoefficient - 1"
                            />
                          </el-form-item>
                          <div class="page-table-input-number-item-unite">
                            {{ scope.row.calcUnitName }}
                          </div>
                        </div>
                      </div>
                      <div
                        v-if="scope.row.qtyOperateMode === 2"
                        class="page-table-input-number-right"
                      >
                        {{ $fn.qtyFormatter(scope.row.qty) }}
                      </div>
                    </div>
                  </el-form-item>
                  <span v-else>{{ $fn.qtyFormatter(scope.row.qty) }}</span>
                </template>
              </page-table>
            </el-form>
          </div>
        </div>
      </div>
    </NewFullScreen>
  </div>
</template>

<script setup name="useApplicationModify">
import { createUseApplication, updateUseApplication } from '@/api/use'
import { getCustomizeSetting } from '@/api/customize'
import { postPrintQrCodeScan, getDepotById } from '@/api/core'
import utils from '@/common/js/utils'
import { ElMessageBox } from 'element-plus'

const { proxy } = getCurrentInstance()
const emits = defineEmits()
const props = defineProps(['visible', 'title', 'id', 'depotInfo', 'detailData'])

console.log(props.depotInfo)
const systemConfig = ref(proxy.$store.state.permission.systemConfig)
const formRefs = ref([])
const scanApi = ref(postPrintQrCodeScan)
const scanFilter = ref({})
//表单相关
const formInfo = ref({
  ref: null,
  data: {
    applicationUserName: proxy.$store.state.user.userInfo.user
      ? proxy.$store.state.user.userInfo.user.name
      : '',
    deptName: '',
    deptId: '',
    depotName: props.depotInfo.depotName,
    depotId: props.depotInfo.depotId,
    exportDepotName: props.depotInfo.exportDepotName,
    exportDepotId: props.depotInfo.exportDepotId,
    exportDeptName: props.depotInfo.exportDeptName,
    exportDeptId: props.depotInfo.exportDeptId,
  },
  fieldList: [
    {
      label: '领用人',
      value: 'applicationUserName',
      type: 'input',
      disabled: true,
    },
    {
      label: '领入仓库',
      value: 'depotName',
      type: 'slot',
    },
    {
      label: '领用部门',
      value: 'deptName',
      type: 'input',
      disabled: true,
    },
    {
      label: '领出仓库',
      value: 'exportDepotName',
      type: 'slot',
    },
    {
      label: '领出部门',
      value: 'exportDeptName',
      type: 'input',
      disabled: true,
    },
    {
      label: '备注',
      value: 'remark',
      type: 'textarea',
    },
  ],
  rules: {
    depotName: [
      {
        required: true,
        message: '请选择领入仓库',
        trigger: 'change',
      },
    ],
    exportDepotName: [
      {
        required: true,
        message: '请选择出库仓库',
        trigger: 'change',
      },
    ],
    deptName: [{ required: true, message: '请输入领用部门', trigger: 'blur' }],
    exportDeptName: [
      { required: true, message: '请输入领出部门', trigger: 'blur' },
    ],
  },
  labelWidth: '120px',
})
const filterInfo = ref({
  query: {
    customizeUserVO: {},
    queryMap: {
      orderId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: props.id,
      },
    },
  },
})
// 表格相关
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  data: [],
  selections: [],
  summaryFieldList: [
    {
      value: 'qty',
      formatter: proxy.$fn.qtyFormatter,
    },
    { value: 'price', show: 'false' },
    {
      value: 'sumAmount',
      formatter: proxy.$fn.TripartiteMethod,
    },
  ],
  fieldList: [],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '50',
    btList: [
      {
        label: '删除',
        event: deleteProduct,
        show: true,
      },
    ],
  },
})

const showDialog = computed({
  get() {
    return props.visible
  },
  set(newValue) {
    emits('update:visible', newValue) // 更新父组件visible
  },
})
const canSave = computed(() => {
  return tableInfo.value.data.length
})

watch(
  () => tableInfo.value.data,
  () => {
    tableInfo.value.data.forEach((row) => {
      let smallUnitQty = parseFloat(row.smallUnitQty || 0)
      let unitConvertCoefficient = parseFloat(row.unitConvertCoefficient || 1)
      let largeUnitQty = parseFloat(row.largeUnitQty || 0)
      let calcQty = proxy.$fn.accAdd(
        proxy.$fn.accMul(largeUnitQty, unitConvertCoefficient),
        smallUnitQty
      )
      let qty = proxy.$fn.qtyFormatter(
        proxy.$fn.accDiv(calcQty, unitConvertCoefficient)
      )
      row['calcQty'] = calcQty
      row['qty'] = qty
      row.sumAmount = proxy.$fn.accMul(
        proxy.$fn.accAdd(
          proxy.$fn.accDiv(smallUnitQty, unitConvertCoefficient),
          largeUnitQty
        ),
        parseFloat(row.price)
      )
      row.productionDate =
        row.productionDate === '1900-01-01' ? undefined : row.productionDate
    })
  },
  {
    deep: true,
  }
)

onMounted(() => {
  proxy.$nextTick(() => {
    formRefs.value = [proxy.$refs['tableForm'], formInfo.value.ref]
  })
  getDept()
})

setData()
function setData() {
  let obj = {
    orderNo: {
      label: '单号',
      value: 'orderNo',
      componentType: 'input',
      show: false,
      // type: 'slot',
      hidden: true,
    },
    qty: {
      label: '数量',
      value: 'qty',
      type: 'slot',
      rules: {
        validator: proxy.$validate.positive,
        trigger: 'blur',
      },
      minWidth: '250px',
      hidden: true,
    },
    storeStockQty: {
      label: '领入仓库可用数量',
      value: 'storeStockQty',
      hidden: true,
      type: 'column',
      formatter: utils.qtyFormatter,
    },
    exportStockQty: {
      label: '领出仓库可用数量',
      value: 'exportStockQty',
      hidden: true,
      type: 'column',
      formatter: utils.qtyFormatter,
    },
    price: {
      label: '单价',
      value: 'price',
      minWidth: '150px',
      type: 'column',
      formatter: proxy.$fn.TripartiteMethod,
      permission: !proxy.$permission('useApplication:price'),
      hidden: true,
    },
    sumAmount: {
      label: '总金额',
      value: 'sumAmount',
      type: 'column',
      formatter: proxy.$fn.TripartiteMethod,
      permission: !proxy.$permission('useApplication:price'),
      hidden: true,
    },
    productionDate: {
      label: '生成日期',
      value: 'productionDate',
      type: 'slot',
      minWidth: '160px',
      hidden: true,
    },
    validityDate: {
      label: '失效日期',
      value: 'validityDate',
      minWidth: '160px',
      type: 'slot',
      hidden: true,
    },
    batchNumber: {
      label: '批号',
      value: 'batchNumber',
      type: 'slot',
      hidden: true,
    },
    defaultSupplierName: {
      label: '默认供应商',
      value: 'defaultSupplierName',
      type: 'column',
      hidden: true,
    },
    defaultSupplierCode: {
      label: '默认供应商编码',
      value: 'defaultSupplierCode',
      type: 'column',
      hidden: true,
    },
    defaultSupplierPrice: {
      label: '默认供应商价格',
      value: 'defaultSupplierPrice',
      type: 'column',
      formatter: proxy.$fn.TripartiteMethod,
      permission: !proxy.$permission('useApplication:price'),
      hidden: true,
    },
    preExportQty: {
      label: '预出库数量',
      value: 'preExportQty',
      type: 'column',
      show: false,
      hidden: true,
    },
    exportQty: {
      label: '出库数量',
      value: 'exportQty',
      type: 'column',
      show: false,
      hidden: true,
    },
    storeQty: {
      label: '入库数量',
      value: 'storeQty',
      type: 'column',
      show: false,
      hidden: true,
    },
  }
  tableInfo.value.fieldList = Object.values({
    ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
    ...obj,
  })
  getCustomize()
  if (!props.id) {
    formInfo.value.fieldList = formInfo.value.fieldList.filter(
      (item) => item.value !== 'orderNo'
    )
  }
}
function getDept() {
  if (formInfo.value.data.depotId && formInfo.value.data.depotId !== -2) {
    getDepotById(formInfo.value.data.depotId).then((res) => {
      if (res && res.success) {
        formInfo.value.data.deptName = res.data.deptName
        formInfo.value.data.deptId = res.data.deptId
      }
    })
  }
}
function changeLarge(e, str) {
  proxy.$refs.tableForm.clearValidate(str)
}
function getList() {
  tableInfo.value.data = props.detailData
}
function getCustomize() {
  let param = {
    tableKey:
      'useApplicationOrderModify-com.slip.spd.entity.vo.use.UseApplicationOrderDetailVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      tableInfo.value.fieldList = proxy.$fn.setFieldList(
        tableInfo.value.fieldList,
        data.detail
      )
      filterInfo.value.query.customizeUserVO = data
      getList()
    }
  })
}
// 触发事件
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.value.selections = data
      break
  }
}
//删除产品
function deleteProduct(data = undefined) {
  proxy
    .$confirm('删除后将改变数据,是否继续?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    .then(() => {
      if (tableInfo.value.selections.length > 0) {
        tableInfo.value.data = tableInfo.value.data.filter(
          (row) => !tableInfo.value.selections.includes(row)
        )
      } else if (data && data.id) {
        tableInfo.value.data = tableInfo.value.data.filter(
          (row) => data !== row
        )
      }
    })
}
//保存
function save() {
  proxy.$fn.checkForm(formRefs.value).then(() => {
    let details = tableInfo.value.data.filter((row) => row.productId && row.qty)
    if (!details.length) {
      proxy.$message({
        duration: 3500,
        type: 'warning',
        showClose: true,
        message: '请添加有效的产品',
      })
      return
    }

    details = details.map((detail) => {
      if (!detail.exportStockQty) {
        detail.exportStockQty = 0
      }
      return detail
    })

    const errorStockProduct = details
      .filter((detail) => detail.qty > detail.exportStockQty)
      .map((detail) => detail.commonName)
    if (errorStockProduct.length) {
      if (systemConfig.value.allow_use_qty_greater_stock === 0) {
        proxy.$message({
          duration: 3500,
          type: 'error',
          showClose: true,
          message: `产品【${errorStockProduct}】申请数量不能大于领出仓库可用数量`,
        })
        return
      } else {
        ElMessageBox.confirm(
          `产品【${errorStockProduct}】申请数量大于领出仓库可用数量`,
          '提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          }
        )
          .then(() => {
            const data = formInfo.value.data
            data.details = details
            data.type = 'use'

            const api = data.id ? updateUseApplication : createUseApplication
            api(data).then((resp) => {
              if (resp && resp.success) {
                showDialog.value = false
                // emits('returnModify')
                proxy.$router.push('/use/application')
              }
            })
          })
          .catch(() => {})
      }
    } else {
      const data = formInfo.value.data
      data.details = details
      data.type = 'use'

      const api = data.id ? updateUseApplication : createUseApplication
      api(data).then((resp) => {
        if (resp && resp.success) {
          showDialog.value = false
          // emits("returnModify");
          //跳转到领用申请
          proxy.$router.push('/use/application')
        }
      })
    }
  })
}
</script>

<style scoped></style>
